package org.mozhu.mboot.admin.system.group.service;

import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.mozhu.mboot.core.data.BaseService;
import org.mozhu.mboot.admin.system.group.entity.UserGroupRelation;
import org.mozhu.mboot.admin.system.group.repository.UserGroupRelationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * 用户分组关系 - 业务层实现类
 *
 * @author mozhu
 */
@Transactional
@Service(value = "userGroupRelationService")
public class UserGroupRelationServiceImpl extends BaseService<UserGroupRelation, Long> implements UserGroupRelationService {

    @Autowired
    GroupService groupService;

    protected UserGroupRelationRepository getBaseRepository() {
        return (UserGroupRelationRepository) baseRepository;
    }

    @Override
    public void appendRelationToUser(Long groupId, Set<Long> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return;
        }
        for (Long userId : userIds) {
            if (userId == null) {
                continue;
            }
            UserGroupRelation r = this.getBaseRepository().findByGroupIdAndUserId(groupId, userId);
            if (r == null) {
                r = new UserGroupRelation();
                r.setGroupId(groupId);
                r.setUserId(userId);
                save(r);
            }
        }
    }

    @Override
    public Set<Long> findGroupIds(Long userId) {
        return Sets.newHashSet(this.getBaseRepository().findGroupIds(userId));
    }

    @Override
    public Set<Long> findAvailableGroupIds(Long userId) {
        Set<Long> groupIds = Sets.newHashSet();
        groupIds.addAll(groupService.findDefaultGroupIds());
        groupIds.addAll(findGroupIds(userId));

        Set<Long> activatedGroupIds = groupService.findAllActivatedGroupIds();
        return Sets.intersection(groupIds, activatedGroupIds).immutableCopy();
    }

}
